// net_fread_all.c
#include "net_file.h"
#include "net_file_all.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "net_file_decompress.h"

NetData* net_fread_all(const char* url) {
    size_t bytesRead;                 // 每次读取的字节数
    char *buffer = (char*)malloc(BUFFER_SIZE);         // 临时读取缓冲区

    if (buffer == NULL) {
        fprintf(stderr, "内存分配失败！\n");
        return NULL;
    }

    NetFile* netFile = net_fopen(url, "r");
    if (netFile == NULL) {
        fprintf(stderr, "无法打开URL: %s\n", url);
        free(buffer);
        return NULL;
    }

    NetData* result = (NetData*)malloc(sizeof(NetData));
    if (result == NULL) {
        fprintf(stderr, "内存分配失败！\n");
        net_fclose(netFile);
        free(buffer);
        return NULL;
    }

    result->data = NULL;
    result->size = 0;
    result->offset = 0; // 初始化 offset

    size_t totalSize = 0;  // 已读取的总数据大小
    size_t capacity = 0;   // 当前分配的缓冲区容量

    while ((bytesRead = net_fread(buffer, 1, BUFFER_SIZE, netFile)) > 0) {
        if (totalSize + bytesRead > capacity) {
            // 扩展内存容量
            size_t newCapacity = (capacity == 0) ? (BUFFER_SIZE * 2) : (capacity * 2);
            char* newData = (char*)calloc(newCapacity, 1);  // 使用 calloc 分配并初始化为零
            if (newData == NULL) {
                fprintf(stderr, "内存分配失败！\n");
                free(result->data);
                free(result);
                free(buffer);
                net_fclose(netFile);
                return NULL;
            }

            // 复制旧数据到新分配的内存
            if (result->data != NULL) {
                memcpy(newData, result->data, totalSize);
                free(result->data);  // 释放旧的内存
            }

            result->data = newData;
            capacity = newCapacity;
        }

        // 将读取的数据复制到结果缓冲区中
        memcpy(result->data + totalSize, buffer, bytesRead);
        totalSize += bytesRead;
    }

    if(netFile->isGzip) {
        // 解压缩数据
        char *decompressedData = calloc(1, totalSize *10); // 假设压缩率是 10 倍
        if(decompressedData == NULL) {
            fprintf(stderr, "内存分配失败！\n");
            free(result->data);
            free(result);
            net_fclose(netFile);
            return NULL;
        }
        size_t totalDecommpressedSize = 0;
        if(Z_OK == decompress_gzip((unsigned char*)result->data, totalSize, (unsigned char*)decompressedData, totalSize*10, &totalDecommpressedSize)) {
            free(result->data);
            result->data = decompressedData;
            result->size = totalDecommpressedSize;
        }else{
            free(decompressedData);
        }
    }else{
        result->size = totalSize;
    }

    // 关闭网络文件
    net_fclose(netFile);
    free(buffer);
    return result;
}


// 用于释放 NetData 结构的内存
void net_fread_all_free(NetData* netData)
{
    if (netData) {
        if (netData->data) {
            free(netData->data);
        }
        free(netData);
    }
}
